﻿using Microsoft.EntityFrameworkCore;
using Yz.Core.Base;
using Yz.Core.Extensions;
using Yz.DataAccess.DbAccessses.Interface;
using Yz.DB.EFCore.Dal;
using Yz.Model.Constants;
using Yz.Model.Entities;
using Yz.Model.Enums;

namespace Yz.DataAccess.DbAccessses
{
    public class YzInitializer : IDependency, IYzInitializer
    {
        private readonly YzContext _yzContext;
        public YzInitializer(YzContext yzContext)
        {
            _yzContext = yzContext;
        }

        public async Task InitDataAsync()
        {
            await AddAdminAsync();
        }
        /// <summary>
        /// 初始化admin
        /// </summary>
        private async Task AddAdminAsync()
        {
            if (!await _yzContext.Users.AsNoTracking().AnyAsync(p => p.UserType == UserType.Admin))
            {
                var returnCode = await _yzContext.Users.AddAsync(new User()
                {
                    LoginName = DefaultConstant.Admin,
                    LoginPwd = DefaultConstant.Password.ToMd5Hash(),
                    CompanyId = 0,
                    UserType = UserType.Admin,
                    Name = "超级管理员",
                    Remark = "超级管理员",
                });
                await _yzContext.SaveChangesAsync();
            }
        }
        /// <summary>
        /// 迁移数据库
        /// </summary>
        /// <returns></returns>
        public async Task MigrateDbAsync()
        {
            if (_yzContext.Database.GetPendingMigrations().Any())
            {
                await _yzContext.Database.MigrateAsync();//自动执行迁移
            }
        }

    }
}
